<template>
	<u-upload
		:ref="`upload${keys}`"
		:fileList="fileList"
		@afterRead="afterRead"
		@delete="deletePic"
		@beforeRead="beforeRead"
		:multiple="multiple"
		:maxCount="maxCount"
		:accept="accept"
		:capture="capture"
		:camera="camera"
		:maxSize="maxSize"
		:useBeforeRead="true"
		:previewFullImage="true"
		:name="`upload${keys}`"
		:class="isRead === true? 'isRead': ''"
	></u-upload>
</template>

<script setup lang="ts" name="UploadImageSSR">
import { ref, toRefs, watch } from 'vue';
/**
 * UploadImage 上传插件
 * @description 支持图片/视频等
 * @property {Array} list 回显图片 [{url: 'https://cdn.uviewui.com/uview/swiper/1.jpg'}]
 * @property {Boolean} multiple = [true | false] 是否支持多选
 * @property {Number} maxCount = 10 最大上传个数
 * @property {String} accept = [image | video | file...] 上传类型
 * @property {String} capture = [camera | album] 上传方式 文件|拍照
 * @property {String} camera = [back | front] 摄像头设置
 * @event {Function} fileChange fileList更新事件
 * @example <upload-image @fileChange="getImages" :list="umodel.images"></upload-image>
 */

const emit = defineEmits(['fileChange']);

const props = defineProps({
	list: {
		type: Array,
		default() {
			return [];
		}
	},
	multiple: {
		type: Boolean,
		default: true
	},
	maxCount: {
		type: Number,
		default: 10
	},
	accept: {
		type: String,
		default: 'image'
	},
	capture: {
		type: [String, Array],
		default: 'camera'
	},
	camera: {
		type: String,
		default: 'back'
	},
	maxSize: {
		type: Number,
		default: Number.MAX_VALUE
	},
	keys: {
		type: Number,
		default: 1
	},
	isRead: {
		type: Boolean,
		default: false
	},
	// 上传统一文件夹名称
  folderName: {
	type: String,
	default: "test/info",
  },
});

const { isRead, keys, list, capture, camera, accept, multiple, maxCount, maxSize, folderName } = toRefs(props);

const uploadApi = process.env.VITE_APP_UPLOAD_API;

// 预览url前缀
const upPreviewUrl = `${uploadApi}/system/fileCenter/preview/`;

const fileList = ref<any[]>([]);

const realList = ref();
watch(()=>fileList,(newVal)=>{
	const lists = JSON.parse(JSON.stringify(newVal.value))
	lists.forEach((item)=>{
		item.url = item.realUrl
		delete item.realUrl
	})
	// console.log('realList.value111', lists)
	realList.value = lists
	setTimeout(()=>{emit('fileChange', realList.value);},100)
}, {
	deep: true
})

watch(
  () => list,
  (newFile) => {
    fileList.value = handleImageUrl(newFile.value);
  },
  {
    immediate: true,
  }
);

// 图片链接处理
function handleImageUrl(list) {
	
	const list1 = JSON.parse(JSON.stringify(list)) ?? []
	
	list1?.forEach((item) => {
		// console.log('handleImageUrl', item)
		item.realUrl = item.url;
		item.url = `${upPreviewUrl}${item.realUrl}`;
	});
	return list1;
}

// 删除图片
const deletePic = (event) => {
	fileList.value.splice(event.index, 1);
	setTimeout(()=>{emit('fileChange', realList.value);},100)
};

// 读取图片
const beforeRead = (event) => {
	// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
	const lists = [].concat(event.file);
	lists.map((item) => {
		if (item.size > maxSize.value) {
			uni.showToast({
				title: `文件不能超过${maxSize.value / 1024 / 1024}M`,
				icon: 'none'
			});
		}
	});
};

// 新增图片
const afterRead = async (event) => {
	// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
	let lists = [].concat(event.file);
	let fileListLen = fileList.value.length;
	lists.map((item) => {
		fileList.value.push({
			...item,
			status: 'uploading',
			message: '上传中'
		});
	});
	for (let i = 0; i < lists.length; i++) {
		try {
			const result = await uploadFilePromise(lists[i].url);
			let item = fileList.value[fileListLen];
			// console.log('result', result)
			// item
			fileList.value.splice(fileListLen, 1, {
				...item,
				status: 'success',
				message: '',
				name: result.originalFilename,
				originalfilename: result.originalFilename,
				filename: result.fileName,
				fileType: result.fileType,
				path: result.path,
				realUrl: result.url,
				url: `${upPreviewUrl}/${result.url}`
			});
			fileListLen++;
		} catch (e) {
			// 上传失败，提示用户
			uni.showToast({
				title: e,
				icon: 'none'
			});
			fileList.value.splice(fileListLen, 1);
			fileListLen++;
		}
	}
	
	setTimeout(()=>{emit('fileChange', realList.value);},100)
};

const uploadFilePromise = (url: string) => {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: `${uploadApi}/system/fileCenter/uploadFile/${folderName.value}`, // 仅为示例，非真实的接口地址
			filePath: url,
			name: 'file',
			formData: {
				user: 'test'
			},
			success: (res) => {
				const result = JSON.parse(res.data);
				if (result.code === 200) {
					resolve(result.data);
				} else {
					reject(result.message);
				}
			}
		});
	});
};

</script>

<style lang="scss" scoped>
	.isRead {
		:deep(.u-upload__button) {
			display: none;
		}
		:deep(.u-upload__deletable) {
			display: none;
		}
	}
</style>